package GoodsService

import (
	"context"
	toolsDb "gdshop-back-end-go/common/db"
	"gdshop-back-end-go/common/response/GoodsResp"
	"github.com/gogf/gf/frame/g"
	"strings"
)

// GetGoodsOptionsByGoodsId 获取规格库存，只显示 is_open = 1 的规格
func GetGoodsOptionsByGoodsId(ctx context.Context, goodsId int, limit int) []*GoodsResp.GoodsOption {
	var goodsOptions []*GoodsResp.GoodsOption
	goDb := toolsDb.GetUnSafaTableAddDeleteWhere(
		ctx,
		"goods_option").Where("goods_id=? AND is_open=1",
		goodsId,
	).Order("display_sort DESC")
	if limit > 0 {
		goDb = goDb.Limit(limit)
	}
	err := goDb.Structs(&goodsOptions)
	if err != nil {
		return nil
	}
	for _, item := range goodsOptions {
		item.TitleArr = strings.Split(item.Title, ";")
		item.Title = strings.ReplaceAll(item.Title, ";", ",")
	}
	return goodsOptions
}

// GetGoodsOptionsTuanByGoodsId 获取带团购信息的商品规格
func GetGoodsOptionsTuanByGoodsId(ctx context.Context, activityId int, goodsId int) []*GoodsResp.GoodsOption {
	var goodsOptions []*GoodsResp.GoodsOption
	goDb := toolsDb.GetUnSafaTableAddDeleteWhere(
		ctx,
		"goods_option").Where("goods_id=? AND is_open=1",
		goodsId,
	).Order("display_sort DESC")
	err := goDb.Structs(&goodsOptions)
	if err != nil {
		return nil
	}
	for _, item := range goodsOptions {
		item.TitleArr = strings.Split(item.Title, ";")
		item.Title = strings.ReplaceAll(item.Title, ";", ",")
	}

	// 获取 gd_goods_activity_goods_list 表中的数据
	gaglList, err := GetActivityOptionByWhere(ctx, int64(activityId), g.Map{
		"go.delete_at < ?": 1,
		"go.is_open = ?":   1,
		"go.goods_id = ?":  goodsId,
		"gagl.id > ? ":     0,
	})
	if err != nil {
		return nil
	}

	var fanhuiOptions []*GoodsResp.GoodsOption
	// 将团购信息添加到 goodsOptions 中
	for _, item := range goodsOptions {
		for _, gagl := range gaglList {
			if gagl.OptionId == int64(item.Id) {
				item.SellPrice = gagl.GaglPrice
				// 处理库存
				if gagl.CustomStock == 2 {
					// 自定义库存
					item.Stock = int(gagl.GaglStock)
				}

				fanhuiOptions = append(fanhuiOptions, item)
			}
		}
	}

	return fanhuiOptions
}
